const router = require('koa-router')()
const svgCaptcha = require('svg-captcha')
const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken');
const mime = require('mime-types');
const tokenSecret = 'mysecretkey';
const filePath = path.join(__dirname, '../public/images')

let users = '';
let info = '';

fs.readFile("./public/data/login.json", "utf8", function (err, dataStr) {
  users = dataStr
})

fs.readFile("./public/data/user.json", "utf8", function (err, data) {
  info = data
})

router.get('/ok', async (ctx, next) => {
  ctx.body = 'ok'
})

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.post('/getUser', async (ctx, next) => {
  // let list = [{"username": "zhangsan", "pwd": "123456"},{"username":"lisi","pwd":"1234"}]; 
  let username = ctx.request.body.username;
  let pwd = ctx.request.body.pwd;
  let captcha = ctx.request.body.captcha.toLowerCase();
  let usersList = JSON.parse(users)
  let isAccount = usersList.filter(e => e.username == username)[0]
  if (captcha === ctx.session.captcha) {
    if (!isAccount) {
      ctx.body = { msg: '账户不存在', token: null }
    } else {
      if (isAccount.pwd == pwd) {
        const token = jwt.sign({ username: username }, tokenSecret, { expiresIn: 60 });
        ctx.session.token = token;
        ctx.body = { msg: '登录成功', token: token };
      } else {
        ctx.body = { msg: '密码错误', token: null }
      }
    }
  } else {
    ctx.body = { msg: '验证码错误', token: null };
  }
})

router.get('/captcha', async (ctx, next) => {
  let captcha = svgCaptcha.create({
    size: 4,
    noise: 2,
    color: true,
    background: "#666",
    width: 123,
    height: 40,
    ignoreChars: '0iloOLI'
  });
  let img = captcha.data; 
  let text = captcha.text.toLowerCase();
  ctx.session.captcha = text;
  ctx.response.type = 'image/svg+xml';
  ctx.body = { "img": img, "text": text };
})

// 文件上传
router.post('/upload', async (ctx, next) => {
  const token = ctx.header.authorization
  if (!token || !ctx.session.token) {
    ctx.body = {
      message: 'token missed'
    }
  } else {
    const files = ctx.request.files.files
    let context = []
    if (files instanceof Array) {
      context = files
    } else {
      context.push(files)
    }
    try {
      for (let file of context) {
        const reader = fs.createReadStream(`${file.filepath}`)
        let filePaths = path.join(__dirname, '../public/images/', `${file.originalFilename}`)
        const upStream = fs.createWriteStream(`${filePaths}`)
        reader.pipe(upStream)
      }
      ctx.body = { code: 200 }
    } catch (error) {
      ctx.body = { msg: error }
    }
  }
});

router.get('/files', async (ctx, next) => {
  try {
    const files = await fs.promises.readdir(filePath);
    const fileData = await Promise.all(
      files.map(async (file) => {
        const filePaths = `http://localhost:3000/images/${file}`;
        const stats = await fs.promises.stat(`${filePath}/${file}`);
        return {
          name: file,
          size: stats.size,
          type: mime.lookup(file),
          path: filePaths,
        };
      })
    );
    ctx.body = fileData;
  } catch (error) {
    console.error(error);
  }
});

router.delete("/del", async (ctx) => {
  try {
    const fileName = ctx.request.query.fileName;
    const filepaths = `${filePath}/${fileName}`;
    await fs.promises.unlink(filepaths);
    ctx.body = fileName;
  } catch (error) {
    console.error(error)
  }
});

router.get('/user', async (ctx, next) => {
  let list = JSON.parse(info)
  ctx.body = list
});

router.post('/addUser', async (ctx, next) => {
  let list = JSON.parse(info)
  list.push(ctx.request.body)
  const str = JSON.stringify(list);
  fs.writeFile('./public/data/user.json', str, function (err, result) {
    if (err) {
      console.log(err)
    }
  });
  ctx.body = { code: 200 };
});

router.post('/alterUser', async (ctx, next) => {
  let list = JSON.parse(info)
  const item = ctx.request.body.index;
  let temp = ctx.request.body
  delete temp.index
  list[item] = temp
  const str = JSON.stringify(list);
  fs.writeFile('./public/data/user.json', str, function (err, result) {
    if (err) {
      console.log(err)
    }
  })
  ctx.body = item;
});

router.delete('/deleteUser', async (ctx, next) => {
  try {
    const item = ctx.request.query.deleteIndex;
    let list = JSON.parse(info)
    list.splice(item, 1)
    const str = JSON.stringify(list);
    fs.writeFile('./public/data/user.json', str, function (err, result) {
      if (err) {
        console.log(err)
      }
    })
    ctx.body = item
  } catch (error) {
    console.error(error)
  }
})

module.exports = router